package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result Getlist() {
        String key = "shop:type:list";
        // 从redis中查，查到了就将取出的string转换为list并返回
        String liststr = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(liststr)){
            List<ShopType> listStr = JSON.parseArray(liststr, ShopType.class);
            return Result.ok(listStr);
        }

        //查不到就从mysql查，查不到返回错误
        List<ShopType> typeList = query().orderByAsc("sort").list();
        if(typeList == null){
            return Result.fail("发生错误，无分类数据");
        }

        // 查到了就将数据从list转化为String，写入redis并返回
        String jsonString = JSON.toJSONString(typeList);
        stringRedisTemplate.opsForValue().set(key, jsonString,30L, TimeUnit.MINUTES);

        return Result.ok(typeList);
    }
}
